package com.liesp.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.livesky.framework.miniapp.ActionContext;

import net.news.entity.NewsPeople;

/**
 * 项目名称：cmunews3084<br>
 * 类名称：OnlineFilter <br>
 * 类描述： 登录过滤器 创建人：charles 创建时间：2011-5-16 下午05:14:37 <br>
 * 修改人： 修改时间： <br>
 * 修改备注：
 * 
 * @version V1.0
 */

public class OnlineFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("/pages/news/login_user/");// 这里设置如果没有登陆将要转发到的页面
		String page = ((HttpServletRequest) request).getHeader("Referer");
		RequestDispatcher dispatcher1 = request
				.getRequestDispatcher(page);
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession(true);
		int requestURI = ((HttpServletRequest) request).getRequestURI()
				.indexOf(".jsp");
		System.out.println(page);
		System.out.println(((HttpServletRequest) request).getRequestURI()
				.indexOf("/pages/")
				+ "------" + ((HttpServletRequest) request).getRequestURI());

		// 从session里取的用户名信息
		NewsPeople newsPeople = (NewsPeople) session
				.getAttribute(ConstantUtils.USER_LOGIN_SESSIOIN);// 这里获取session，为了检查session里有没有保存用户信息，没有的话回转发到登陆页面
		// 判断如果没有取到用户信息,就跳转到登陆页面
		if (newsPeople == null) {
			response.setContentType("text/html;charset=utf-8");
			response
					.getWriter()
					.println(
							"<div style='margin: 100 auto;text-align: center;  "
									+ "font: bold 18px 宋体;color: #0066CC;vertical-align: middle'> Sorry,您没有权限访问该资源!</div>");
			// 跳转到登陆页面
			dispatcher.forward(request, response);
			System.out.println("用户没有登陆，不允许操作");

			res.setHeader("Cache-Control", "no-store");
			res.setDateHeader("Expires", 0);
			res.setHeader("Pragma", "no-cache");
		} else {
			// 已经登陆,继续此次请求
				chain.doFilter(request, response);
				System.out.println("用户已经登陆，允许操作");
		}
	}

	public void destroy() {

	}
}
